/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { DatePicker } from 'antd';
import moment from 'moment';
import type { Moment } from 'moment';
import React, { useState } from 'react';
import { useCompareWindowSize } from '@base/hooks/win';

const { RangePicker } = DatePicker;

type RangeValue = [Moment | null, Moment | null] | null;

export const defaultDateRange = [moment().subtract(6, 'days'), moment()];
export const defaultDateRange30 = [moment().subtract(30, 'days'), moment()];

const KbDateRange: React.FC<any> = (props) => {
  const { limitMaxRangeDays = 365, limitSingleRangeDays = 30, value, placeholder, ...rest } = props;

  const isSM = useCompareWindowSize('sm');
  const [dates, setDates] = useState<RangeValue>(null);

  const isInDateRange = (cur: Moment, d: Moment | null, limit = 30) => {
    const range = {
      start: moment(d).subtract(limit, 'days'),
      end: moment(d).add(limit, 'days'),
    };
    return cur.isBetween(range.start, range.end);
  };

  const disabledDate = (current: Moment) => {
    // 限制可选最大区间
    const rangeDate = {
      start: moment().subtract(limitMaxRangeDays, 'days'),
      end: moment(),
    };
    const isInRange = current.isBetween(moment(rangeDate.start), moment(rangeDate.end));
    if (!isInRange) {
      return true;
    }
    if (!dates) {
      return false;
    }
    // 限制单次选择区间
    const [first, end] = dates || [];
    if (first) {
      return !isInDateRange(current, first, limitSingleRangeDays);
    }
    if (end) {
      return !isInDateRange(current, end, limitSingleRangeDays);
    }
    return false;
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      setDates([null, null]);
    } else {
      setDates(null);
    }
  };

  return (
    <RangePicker
      value={dates || value}
      disabledDate={disabledDate}
      onCalendarChange={(v) => setDates(v)}
      onOpenChange={onOpenChange}
      inputReadOnly={isSM}
      format='YYYY-MM-DD'
      {...rest}
    />
  );
};

export default KbDateRange;
